const { query } = require('../../../lib/db');
const { authenticateToken } = require('../../../lib/auth');

async function handler(req, res) {
  if (req.method !== 'GET') {
    return res.status(405).json({
      success: false,
      message: '方法不允许'
    });
  }

  try {
    // 查询当前用户详细信息
    const users = await query(
      `SELECT u.*, t.name as tenant_name, t.code as tenant_code 
       FROM users u 
       LEFT JOIN tenants t ON u.tenant_id = t.id 
       WHERE u.id = ? AND u.status = 1`,
      [req.user.id]
    );

    if (users.length === 0) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    const user = users[0];

    // 返回用户信息（不包含密码）
    const userData = {
      id: user.id,
      username: user.username,
      name: user.name,
      employee_id: user.employee_id,
      department: user.department,
      tenant_id: user.tenant_id,
      tenant_name: user.tenant_name,
      tenant_code: user.tenant_code,
      email: user.email,
      phone: user.phone,
      role: user.role,
      last_login_at: user.last_login_at,
      created_at: user.created_at
    };

    res.status(200).json({
      success: true,
      data: userData
    });

  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

export default authenticateToken(handler);